<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getNewFriendRequests, agreeRequest, ignoreRequest } from '@/api/relation.ts';
import {ElMessage} from "element-plus";
// 工具函数：从Token解析用户ID（根据实际Token结构调整字段）
const getUserIdFromToken = (token: string) => {
  if (!token) return '';
  try {
    const payloadBase64 = token.split('.')[1];
    const decoded = JSON.parse(atob(payloadBase64));
    return decoded.sub; // 假设用户ID存放在JWT的sub字段
  } catch (error) {
    console.error('Token解析失败:', error);
    return '';
  }
};
// 获取当前用户ID
const getCurrentUserId = (): number => {
  const token = localStorage.getItem('token');
  const userId = getUserIdFromToken(token);
  return userId ? Number(userId) : 6
};

const router = useRouter();
const currentUserId = getCurrentUserId();
const requests = ref<any[]>([]); // 好友申请列表

// 原生时间格式化
const formatTime = (timeStr: string) => {
  const date = new Date(timeStr);
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${month}-${day} ${hours}:${minutes}`;
};

// 获取待处理申请
onMounted(async () => {
  try {
    const res = await getNewFriendRequests(currentUserId);
    // 后端返回 Result 对象，需提取 res.data.data
    if (res.data.code === 200) {
      requests.value = res.data.data || []; // 正确提取数据列表
    } else {
      console.error('获取申请失败：', res.data.msg);
    }
  } catch (error) {
    console.error('加载申请失败：', error);
  }
});

// 同意申请
const handleAgree = async (requestId: number) => {
  try {
    await agreeRequest(requestId);
    // 刷新列表
    const res = await getNewFriendRequests(currentUserId);
    requests.value = res.data || [];
    ElMessage.success('同意好友申请成功！')
  } catch (error) {
    ElMessage.error('同意好友申请失败，请重试');
  }
};

// 忽略申请
const handleIgnore = async (requestId: number) => {
  try {
    await ignoreRequest(requestId);
    // 刷新列表
    const res = await getNewFriendRequests(currentUserId);
    requests.value = res.data || [];
    ElMessage.warning('已忽略好友申请')
  } catch (error) {
    alert('忽略失败，请重试');
  }
};
const goToAddFriend = () => {
  const currentUserId = getCurrentUserId();
  router.push({
    path: '/addFriend',
    query: {currentUserId: currentUserId.toString()} // 传参：currentUserId
  });
};
</script>

<template>
  <div class="new-friend-page">
    <!-- 顶部导航 -->
    <header class="new-friend-header">
      <div class="back-btn" @click="router.back()">
        <svg class="icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
        </svg>
      </div>
      <h1 class="header-title">新的朋友</h1>
      <div class="add-btn" @click="goToAddFriend">添加朋友</div>
    </header>

    <!-- 搜索框 -->
    <div class="search-container">
      <input type="text" placeholder="搜索 账号/手机号" class="search-input">
    </div>

    <!-- 申请列表 -->
    <div class="request-list">
      <!-- 空状态 -->
      <div v-if="requests.length === 0" class="empty-state">
        <p>暂无新的好友申请</p>
      </div>

      <!-- 申请项 -->
      <div
          v-for="item in requests"
          :key="item.id"
          class="request-item"
      >
        <div class="avatar-container">
          <img
              :src="item.avatar || 'https://picsum.photos/200'"
              alt="申请人头像"
              class="avatar"
          />
        </div>
        <div class="info-container">
          <div class="name-row">
            <span class="name">{{ item.username}}</span>
            <span class="time">{{ formatTime(item.createTime) }}</span>
          </div>
          <div class="request-msg">{{ item.requestMsg || '无申请说明' }}</div>
          <div class="action-buttons">
            <button class="agree-btn" @click="handleAgree(item.id)">同意</button>
            <button class="ignore-btn" @click="handleIgnore(item.id)">忽略</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 根容器 */
.new-friend-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", sans-serif;
}


.container {
  width: 100%;
  max-width: 420px;
  box-sizing: border-box;
}

/* 顶部导航 左右按钮  中间标题 */
.new-friend-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 44px;
  padding: 0 16px;
  border-bottom: 1px solid #eee;
  background-color: #f7f7f7;
  box-sizing: border-box;
}

.back-btn {
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.icon {
  width: 22px;
  height: 22px;
  color: #333;
}

.header-title {
  font-size: 17px;
  font-weight: 600;
  margin: 0;
  color: #333;
}

.add-btn {
  font-size: 14px;
  color: #07c160;
  cursor: pointer;
  white-space: nowrap;
}

/* 搜索框 */
.search-container {
  padding: 8px 16px;
  background-color: #f7f7f7;
  box-sizing: border-box;
}

.search-input {
  width: 100%;
  height: 36px;
  padding: 0 32px 0 16px;
  border: 1px solid #eee;
  border-radius: 18px;
  font-size: 14px;
  background: url('data:image/svg+xml;utf8,<svg fill="none" stroke="%23999" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>')
  no-repeat right 10px center;
  background-size: 20px;
  box-sizing: border-box;
}

/* 申请列表*/
.request-list {
  padding: 16px;
  box-sizing: border-box;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
  color: #999;
  font-size: 14px;
}

.request-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 12px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}

.avatar-container {
  width: 56px;
  height: 56px;
  margin-right: 12px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  background-color: #eee;
}

.info-container {
  flex: 1;
  min-width: 0;
}

.name-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}

.name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.time {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
}

.request-msg {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  line-height: 1.4;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.agree-btn {
  background: #07c160;
  color: #fff;
  border: none;
  padding: 6px 14px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.agree-btn:hover {
  background: #06b054;
}

.ignore-btn {
  background: #f5f5f5;
  color: #333;
  border: 1px solid #eee;
  padding: 5px 13px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.ignore-btn:hover {
  background: #eee;
}
</style>